package cn.buglife.springboot.controller.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 利用Spring Boot发送邮件
 *
 * Created by zhangjun on 15/11/30.
 */
@RequestMapping(value = "/email")
@RestController
public class EmailController {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送简单文本邮件
     *
     * @param msg
     * @return
     */
    @RequestMapping(value = "/simple", method = RequestMethod.GET)
    public Map send(@RequestParam(value = "msg") String msg){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("no-reply@buglife.cn");
        simpleMailMessage.setTo("410916081@qq.com");
        simpleMailMessage.setText(msg);
        simpleMailMessage.setSubject("邮件测试");
        javaMailSender.send(simpleMailMessage);

        Map map = new HashMap();
        map.put("success",true);
        return map;
    }


    /**
     * 发送HTML格式邮件
     *
     * @return
     */
    @RequestMapping(value = "/html", method = RequestMethod.GET)
    public Map sendHtml(@RequestParam(value = "msg") String msg){
        InputStream template = EmailController.class.getClassLoader().getResourceAsStream("templates/mail/test.html");
        Scanner scanner = new Scanner(template, "UTF-8");
        String text = MessageFormat.format(scanner.useDelimiter("\\A").next(), msg);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {
            messageHelper.setFrom("no-reply@buglife.cn","Bug Life");
            messageHelper.setTo("410916081@qq.com");
            messageHelper.setSubject("html邮件");
            messageHelper.setText(text, true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("success",true);
        return map;
    }
}
